﻿using QWManage.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BlackList.DAL
{
    public class RecordsDAL : SqlDAL
    {
        public RecordsDAL()
        {
            TableName = "Records";
        }
        public DataTable Search(HashSet<string> fields, DateTime dtStart, DateTime dtEnd)
        {
            string query = $"select {string.Join(",", fields)} from {TableName}";
            DataTable table = new DataTable();
            using (SqlConnection connection = new SqlConnection(SQLCON))
            {
                SqlCommand command = new SqlCommand(query, connection);
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                connection.Open();
                adapter.Fill(table);
            }
            DataTable newTable = table.Clone();
            foreach (DataRow dr in table.Rows)
            {
                if (!newTable.Columns.Contains("CreatedAt")) continue;
                if (dr["CreatedAt"] == null || dr["CreatedAt"] == DBNull.Value) continue;
                string strCreatedAt = (string)dr["CreatedAt"];

                strCreatedAt = strCreatedAt.Replace("T", " ");
                strCreatedAt = Regex.Replace(strCreatedAt, "Z$", "");

                DateTime dtCreatedAt;
                if (!DateTime.TryParse(strCreatedAt, out dtCreatedAt)) continue;

                if (dtCreatedAt >= dtStart && dtCreatedAt <= dtEnd)
                    newTable.ImportRow(dr);
            }
            return newTable;
        }
    }
}
